package api.cie.rss.dal;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class RSS_CategoryDAL {

	public static final String KEY_RSS = "idRSS";
	public static final String KEY_CATEGORY = "idCategory";
	
	private static final String DATABASE_TABLE = "RSS_Category";
	private static final String TABLE_CATEGORY = "Category";
	public static final String KEY_TITLE = "title";
	private SQLiteDatabase database;
	
	public RSS_CategoryDAL(DatabaseAdapter dbAdapter) {
		database = dbAdapter.getDatabase();
	}
	
	/**
	 * Create a new entry. If the entry is successfully created, return the new
	 * rowId for that entry, otherwise return a -1 to indicate failure.
	 */
	public void createRSSCategory(int idRSS, int idCategory) {
		ContentValues initialValues = createContentValues(idRSS, idCategory);

		database.insert(DATABASE_TABLE, null, initialValues);
	}
	
	private ContentValues createContentValues(int idRSS, int idCategory) {
		ContentValues values = new ContentValues();
		values.put(KEY_RSS, idRSS);
		values.put(KEY_CATEGORY, idCategory);
		
		return values;
	}
	
	/**
	 * Deletes an entry
	 */
	public boolean deleteRSSCategory(int idRSS, int idCategory) {
		return database.delete(DATABASE_TABLE, KEY_RSS + "=" + idRSS + " and " 
				+ KEY_CATEGORY + "=" + idCategory, null) > 0;
	}
	
	/**
	 * Deletes an entry
	 */
	public boolean deleteRSSCategoryByRSS(int idRSS) {
		return database.delete(DATABASE_TABLE, KEY_RSS + "=" + idRSS, null) > 0;
	}
	
	
	/**
	 * Return a Cursor positioned at the defined entry
	 */
	public Cursor fetchRSSCategory(int idRSS, int idCategory) throws SQLException {
		Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
				KEY_RSS, KEY_CATEGORY },
				KEY_RSS + "=" + idRSS + " and " + KEY_CATEGORY + "=" + idCategory, 
				null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	/**
	 * Get by RSS
	 * @param idRSS
	 * @param idCategory
	 * @return
	 * @throws SQLException
	 */
	public Cursor fetchByRSS(int idRSS) throws SQLException {
		Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
				KEY_RSS, KEY_CATEGORY },
				KEY_RSS + "=" + idRSS, 
				null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	public Cursor fetchTitleCategoryByRSS(int idRSS) throws SQLException {
		Cursor mCursor = database.query(true, DATABASE_TABLE + "," + TABLE_CATEGORY, new String[] {
				KEY_RSS, TABLE_CATEGORY + "." + KEY_TITLE },
				KEY_RSS + "=" + idRSS + " and " + KEY_CATEGORY +"="+ TABLE_CATEGORY + "._id", 
				null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
}
